<template>
  <div class="user-info app-container">
    <a-breadcrumb>
      <a-breadcrumb-item>租户权限</a-breadcrumb-item>
      <a-breadcrumb-item>菜单配置</a-breadcrumb-item>
      <a-breadcrumb-item>账号设置</a-breadcrumb-item>
    </a-breadcrumb>
    <div class="user-info__container user-info__avatar">
      <div class="user-avatar">
        <img :src="Avatar" />
        <div class="set-avatar">
          <GiSvgIcon name="camera-icon" size="16" />
        </div>
      </div>
      <div class="user-content">
        <div class="user-content-item">
          <div>
            用户名：<span>{{ user.nickName }}</span>
          </div>
          <div class="mt12">
            账号ID：<span>{{ user.userId }}</span>
          </div>
          <div class="mt12">注册时间：<span>2013-05-10 12:10:00</span></div>
        </div>
        <div class="user-content-item">
          <div>
            部门岗位：<span>{{ userStore.mainDeptName }} | {{ userStore.userPost }}</span>
          </div>
          <div class="mt12">
            手机号码：<span>{{ hideMiddleDigits(user.mobile) }}</span>
          </div>
        </div>
      </div>
    </div>
    <div class="user-info__container user-info__setting">
      <a-tabs :default-active-key="activeTabs" @change="changeTabs">
        <a-tab-pane v-if="user.tenantTypeCode === '0'" key="1" title="账户信息">
          <FactoryAccountInfo :detailInfo="zhInfo" ref="accountInfoRef" />
        </a-tab-pane>
        <a-tab-pane v-if="user.tenantTypeCode === '0'" key="2" title="品牌信息">
          <template v-if="zhInfo?.factoryId">
            <FactoryBrandInfo :factoryId="zhInfo?.factoryId" ref="brandInfoRef" />
          </template>
        </a-tab-pane>
        <a-tab-pane key="3" title="安全设置">
          <div class="app-container">
            <!-- <template #title>安全设置</template> -->
            <CustomTitle title="安全设置"></CustomTitle>
            <div class="setting-item">
              <div class="setting-item__pwd">
                <span class="title">登录密码：</span>
                <span class="info">已设置。密码至少6位数，支持数字、字母和除空格外的特殊字符。</span>
              </div>
              <a-button type="text" @click="handelSetPwd">修改</a-button>
            </div>
            <div class="setting-item">
              <div class="setting-item__pwd">
                <span class="title">安全手机：</span>
                <span class="info">{{ user.mobile ? `已绑定：${hideMiddleDigits(user.mobile)}` : "未绑定" }}</span>
              </div>
              <a-button type="text" @click="handelSetPhone">{{ !user.mobile ? "绑定" : "修改" }}</a-button>
            </div>
          </div>
        </a-tab-pane>
        <a-tab-pane key="4" v-if="user.tenantTypeCode === '0'" disabled>
          <template #title>
            <div>
              <a-button v-if="activeTabs === '1'" type="primary" class="mr16" @click="saveInfo">保存</a-button>
              <a-button v-if="activeTabs === '1'" type="outline" @click="getFactoryInfoFun">取消</a-button>
            </div>
          </template>
        </a-tab-pane>
      </a-tabs>
    </div>

    <!--  修改密码  -->
    <a-modal
      :visible="setPwd"
      :closable="false"
      title-align="start"
      modal-class="modal-custom"
      @cancel="handleSetPwdCancel"
      @ok="handleSetPwdOk"
    >
      <template #title> <CustomTitle title="修改密码" /></template>
      <a-form :model="setPwdForm" :rules="setPwdRules" ref="pwdForm">
        <a-form-item field="oldPassword" label="旧密码">
          <a-input placeholder="旧密码" v-model.trim="setPwdForm.oldPassword" />
        </a-form-item>
        <a-form-item field="password" label="新密码">
          <a-input placeholder="新密码" v-model.trim="setPwdForm.password" />
        </a-form-item>
        <a-form-item field="checkPassword" label="确认密码">
          <a-input placeholder="确认密码" v-model.trim="setPwdForm.checkPassword" />
        </a-form-item>
      </a-form>
    </a-modal>
    <!--  修改手机  -->
    <a-modal
      :visible="setPhone"
      :closable="false"
      :mask-closable="false"
      title-align="start"
      @ok="handleSetPhoneOk"
      @cancel="handleSetPhoneCancel"
    >
      <template #title> <CustomTitle title="修改手机号" /></template>
      <a-form :model="setPhoneForm" :rules="setPhoneRules" ref="setPhoneRef">
        <!--        <a-form-item field="oldMobile" label="旧手机号">-->
        <!--          <a-input placeholder="旧手机号" v-model.trim="setPhoneForm.oldMobile" max-length="11"/>-->
        <!--        </a-form-item>-->
        <a-form-item field="newMobile" label="新手机号">
          <a-input placeholder="新手机号" v-model.trim="setPhoneForm.newMobile" :max-length="11" />
        </a-form-item>
        <a-form-item field="smsCode" label="验证码">
          <div class="phone-code">
            <a-input placeholder="验证码" v-model.trim="setPhoneForm.smsCode" :max-length="4" />
            <a-button class="phone-code-btn" @click="handelGetCode" :disabled="isGetCode">{{ codeBtn }}</a-button>
          </div>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import CustomTitle from "@/components/CustomTitle/index.vue";
import Avatar from "@/assets/images/avatar.png";
import { hideMiddleDigits } from "@/utils";
import { updatePassword, updateMobile, getVerifyCodeUpdateMobile, getUserInfo, getFactoryInfo, saveFactoryInfo } from "@/apis";
import type { ChangeMobile } from "@/apis";
import * as Regexp from "@/utils/regexp";
import { Message } from "@arco-design/web-vue";
import { useUserStore } from "@/stores";
import { useRouter } from "vue-router";
import _ from "lodash";
import FactoryAccountInfo from "./components/FactoryAccountInfo.vue";
import FactoryBrandInfo from "./components/FactoryBrandInfo.vue";

const { proxy } = getCurrentInstance();

const userStore = useUserStore();
const router = useRouter();
const accountInfoRef = ref();
const brandInfoRef = ref();
const activeTabs = ref(undefined);

const saveInfo = async () => {
  // console.log("保存工厂端账户信息");
  const { accountInfo, planData } = await accountInfoRef.value.getFormData();
  // const brandForm = brandInfoRef.value.getFormData();
  console.log("账户信息Form===", accountInfo);
  if (JSON.stringify(accountInfo) !== "{}") {
    saveFactoryInfo({ factoryId: zhInfo.value?.factoryId, ...accountInfo }).then(res => {
      if (res.code === 200) {
        Message.success("账户信息保存成功");
        getFactoryInfoFun();
      }
    });
  }
};

/**
 * 账户信息
 */
const zhInfo = ref({});
const getFactoryInfoFun = () => {
  getFactoryInfo({ factoryId: user.value.tenantId }).then(res => {
    if (res.code === 200) {
      console.log("账户信息===", res);
      zhInfo.value = res.data;
    }
  });
};

/**
 * 切换tabs
 */
const changeTabs = val => {
  activeTabs.value = val;
};

/**
 * 用户信息
 */
const user = ref({});
const getUser = async () => {
  await getUserInfo().then(res => {
    user.value = res.data.user;
    if (user.value.tenantTypeCode === "0") {
      activeTabs.value = "1";
    } else {
      activeTabs.value = "3";
    }
  });
};

/**
 * 修改密码
 */
const setPwd = ref(false);
const setPwdForm = ref({
  oldPassword: "",
  password: "",
  checkPassword: ""
});
const validatorPassword = (value: any, callback: Function) => {
  const passwordRegex = /^[0-9a-zA-Z\W_].{5,}$/;
  if (value === "") {
    return callback("请输入密码");
  } else if (value.length < 6) {
    return callback("密码至少6位数");
  } else if (!passwordRegex.test(value)) {
    return callback("密码至少6位数，支持数字、字母和除空格外的特殊字符");
  }
};
const validatorCheckPassword = (value: any, callback: Function) => {
  if (value === "") {
    return callback("请再次输入密码");
  } else if (value !== setPwdForm.value.password) {
    return callback("两次输入密码不一致");
  }
};
const setPwdRules = {
  oldPassword: [{ required: true, message: "旧密码至少6位数", minLength: 6 }, { validator: validatorPassword }],
  password: [{ required: true, message: "新密码至少6位数", minLength: 6 }, { validator: validatorPassword }],
  checkPassword: [{ required: true, message: "密码至少6位数", minLength: 6 }, { validator: validatorCheckPassword }]
};
const handelSetPwd = () => {
  setPwd.value = true;
};
const handleSetPwdCancel = () => {
  setPwd.value = false;
  resetPwd();
};
const handleSetPwdOk = async () => {
  const valid = await proxy.$refs.pwdForm?.validate();
  if (valid) return;
  await updatePassword(setPwdForm.value);
  Message.success("密码修改成功，请重新登录");
  userStore.logout().then(() => {
    router.replace("/login");
    resetPwd();
  });
};
const resetPwd = () => {
  proxy.$refs.pwdForm?.resetFields();
  setPwdForm.value = {
    oldPassword: "",
    password: "",
    checkPassword: ""
  };
};

/**
 * 修改手机
 */
const setPhone = ref(false);
const setPhoneForm = ref<ChangeMobile>({
  newMobile: "",
  smsCode: ""
});
const setPhoneRules = {
  newMobile: [
    { required: true, message: "请输入新手机号" },
    { match: Regexp.Phone, message: "手机号格式不正确" }
  ],
  smsCode: [
    { required: true, message: "请输入验证码" },
    { match: Regexp.Code_4, message: "请输入4位数字验证码" }
  ]
};

const codeBtn = ref("获取验证码");
const isGetCode = ref(false);
let timer: any = null;
let number = 60;
const getCode = async () => {
  if (!setPhoneForm.value.newMobile) {
    return Message.error("请输入新手机号码");
  }
  await getVerifyCodeUpdateMobile(setPhoneForm.value.newMobile);
  timer && clearInterval(timer);
  isGetCode.value = true;
  timer = setInterval(() => {
    codeBtn.value = `重新发送${number--}s`;
    if (number === 0) {
      clearInterval(timer);
      timer = null;
      codeBtn.value = "获取验证码";
      isGetCode.value = false;
    }
  }, 1000);
};
const handelGetCode = _.debounce(getCode, 500);

const handelSetPhone = () => {
  setPhone.value = true;
};
const handleSetPhoneCancel = () => {
  restPhone();
  setPhone.value = false;
};
const handleSetPhone = async () => {
  const valid = await proxy.$refs.setPhoneRef?.validate();
  if (valid) return;
  await updateMobile(setPhoneForm.value);
  handleSetPhoneCancel();
  getUser();
  Message.success("手机号修改成功");
};
const handleSetPhoneOk = _.debounce(handleSetPhone, 500);
const restPhone = () => {
  proxy.$refs.setPhoneRef?.resetFields();
  setPhoneForm.value = {
    newMobile: "",
    smsCode: ""
  };
  clearInterval(timer);
  timer = null;
  isGetCode.value = false;
  number = 60;
  codeBtn.value = "获取验证码";
};

onUnmounted(async () => {
  clearInterval(timer);
  timer = null;
});

onMounted(async () => {
  await getUser();

  if (user.value.tenantTypeCode === "0") {
    // console.log("用户信息===", user.value);
    getFactoryInfoFun();
  }
});
</script>

<style scoped lang="scss">
@import "index";

:deep(.arco-input-wrapper),
:deep(.arco-select-view-single),
:deep(.arco-picker),
:deep(.arco-select-view-multiple),
:deep(.arco-textarea-wrapper) {
  border: none !important;
}
:deep(.arco-select-view-multiple.arco-select-view-disabled) {
  border: 1px solid #dcdfe6 !important;
}

:deep(.arco-tabs-content) {
  padding-top: 0;
}
:deep(.arco-tabs-nav-tab-list) {
  width: 100%;
  .arco-tabs-tab {
    height: 50px;
  }
  .arco-tabs-tab.arco-tabs-tab-disabled {
    float: right;
  }
}
.user-info {
  height: calc(100% - 40px);
}
</style>
